package com.hsy.servlet;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.hsy.pojo.User;
import com.hsy.service.UserService;
import com.hsy.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

@WebServlet("/userSystem/login")
public class LoginServlet extends HttpServlet {
    private UserService userService = new UserServiceImpl();
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setCharacterEncoding("UTF-8"); // 防止post请求乱码，设置请求的参数字符集为UTf-8
        resp.setContentType("application/json;charset=UTF-8");  // // 设置响应头，指定返回数据的格式为JSON以及字符编码
        ObjectMapper objectMapper = new ObjectMapper();
        User user = objectMapper.readValue(req.getInputStream(), User.class);

        boolean loginSuccess = false;
        User loginUser = userService.checkLogin(user);
        loginSuccess = loginUser == null ? false : true;
        Map<String, Object> responseData = new HashMap<>();
        if (loginSuccess) {
            responseData.put("success", true);
            responseData.put("message", "登入成功");
            // 将用户信息存入session，方便后续使用filter以及登入首页时的用户头像使用
            req.getSession().setAttribute("user", loginUser);
            // 然后重定向到UserListServlet，确保登入到home.jsp后能够渲染页面
            // 由于UserListServlet是个Servlet，所以重定向就是调用这个类的doGet请求（http协议默认输入url重定向时是Get2请求）
//            resp.sendRedirect(req.getContextPath() + "/userList");
        } else {
            responseData.put("success", false);
            responseData.put("message", "用户不存在或密码错误");
        }
        // 将响应数据转换为JSON字符串
        String responseJson = objectMapper.writeValueAsString(responseData);
        // 通过PrintWriter将JSON格式的响应数据写回给前端
        PrintWriter writer = resp.getWriter();
        writer.write(responseJson);
        writer.flush();
        writer.close();
    }
}
